import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import { login, getUserInfo, getRights } from '@/api/user'
import { rights, menus } from '@/api/permission'
import { getToken, setToken, removeToken, getId, setId, removeId } from '@/utils/cookies'
import router, { resetRouter } from '@/router'
import { PermissionModule } from './permission'
import { TagsViewModule } from './tags-view'
import store from '@/store'
import { resolve } from 'path'

export interface IUserState {
  token: string
  name: string
  avatar: string
  introduction: string
  roles: string[],
  permission: string[],
  email: string,
  Id: string
}

interface IUser {
  id: number,
  username: string,
  mobile: string,
  email: string,
  [propName: string]: any;
}

interface IPermission {
  id: number,
  authName: string,
  path: string| null,
  pid: number,
  children: any
}

function generatePermission(arrObj: any): string[] {
  const arr:string[] = []
  arrObj.forEach((one:IPermission) => {
    arr.push(one.path + '_' + one.id + '_01')
    if(one.hasOwnProperty('children')){
      one.children.forEach((two:IPermission) => {
        arr.push(two.path + '_' + two.id + '_02')
        if(two.hasOwnProperty('children')){
          two.children.forEach((three:IPermission) => {
            arr.push(three.path + '_' + three.id + '_03')
          })
        }
      })
    }
  });

  return arr
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  public token = getToken() || ''
  public name = ''
  public avatar = ''
  public introduction = ''
  public roles: string[] = []
  public email = ''
  public permission: string[] = []
  public Id!: string

  @Mutation
  private SET_TOKEN(token: string) {
    this.token = token
  }

  @Mutation
  private SET_NAME(name: string) {
    this.name = name
  }

  @Mutation
  private SET_AVATAR(avatar: string) {
    this.avatar = avatar
  }

  @Mutation
  private SET_INTRODUCTION(introduction: string) {
    this.introduction = introduction
  }

  @Mutation
  private SET_ROLES(roles: string[]) {
    this.roles = roles
  }

  @Mutation
  private SET_EMAIL(email: string) {
    this.email = email
  }

  @Mutation
  private SET_ID(Id: string) {
    this.Id = Id
  }

  @Mutation
  private SET_PERMISSION(permissions: string[]) {
    this.permission = permissions
  }

  @Action
  public async Login(userInfo: { username: string, password: string}) {
    let { username, password } = userInfo
    username = username.trim()
    const res: any = await login({ username, password })
    console.log("res", res)
    setToken(res.token)
    setId(res.id)
    this.SET_TOKEN(res.token)
    this.SET_ID(res.id)
  }

  @Action
  public ResetToken() {
    removeToken()
    this.SET_TOKEN('')
    this.SET_ROLES([])
  }

  @Action
  public  GetUserInfo() {
    // if (this.token === '') {
    //   throw Error('GetUserInfo: token is undefined!')
    // }
    // const { data } = await getUserInfo({ /* Your params here */ })
    // if (!data) {
    //   throw Error('Verification failed, please Login again.')
    // }
    // const { roles, name, avatar, introduction, email } = data.user
    // // roles must be a non-empty array
    // if (!roles || roles.length <= 0) {
    //   throw Error('GetUserInfo: roles must be a non-null array!')
    // }
    // this.SET_ROLES(roles)
    // this.SET_NAME(name)
    // this.SET_AVATAR(avatar)
    // this.SET_INTRODUCTION(introduction)
    // this.SET_EMAIL(email)
    return new Promise(async (resolve, reject)=>{
      const id: any = getId()
      const { username } = await getUserInfo(id)
      const res = await getRights()
      console.log("res::", res)
      const permission = generatePermission(res)
      this.SET_NAME(username)
      this.SET_PERMISSION(permission)
      resolve(permission)
    })
  }

  @Action
  public GetPermission() {
    
    return new Promise((resolve, reject) => {
      rights('tree').then( response => {
     
        const permission =  generatePermission(response)
        this.SET_PERMISSION(permission)
        resolve(permission)
      }).catch(error => {
        reject(error)
      })
      menus().then(res=>{
        console.log("menus:::", res)
      })
    })
  }


  @Action
  public async LogOut() {
    if (this.token === '') {
      throw Error('LogOut: token is undefined!')
    }
    removeToken()
    resetRouter()
    removeId()
    this.SET_TOKEN('')
    this.SET_ID('')
  }

}

export const UserModule = getModule(User)
